package com.sunsharing.flow.model.node;

import com.sunsharing.common.anno.Factory;
import com.sunsharing.common.utils.StringUtils;
import com.sunsharing.flow.exe.ExecutionContext;
import com.sunsharing.flow.exe.Token;
import com.sunsharing.flow.model.Node;
import com.sunsharing.flow.model.Transition;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-5-19
 * Time: 下午4:28
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="AndFork")
public class AndFork extends Node {

    /**
     * 功能描述:
     *     执行
     */
    @Override
    public void execute(ExecutionContext executeContext) {

        //把当前节点加入执行节点
        executeContext.getToken().addExecutedNode(this);

        if (this.leavingTransitions == null ||
                this.leavingTransitions.size() == 0) {
            throw new java.lang.IllegalArgumentException("节点[" + this.getId()
                    + "]的离开迁移为空,请检查该节点是否配置离开迁移!");
        }

        Token parentToken = executeContext.getToken();

        //System.out.println("parentToken:"+parentToken);

        Iterator iter = leavingTransitions.iterator();
        String andForkTaskId = StringUtils.genUUID();
        while (iter.hasNext()) {
            //获得离开迁移
            Transition transition = (Transition) iter.next();
            //创建子令牌
            String tokenName = transition.getId();
            Token childToken = new Token(parentToken, tokenName,this,parentToken.getContext(),andForkTaskId);
            //System.out.println("childToken:"+childToken);
            //创建执行上下文
           // ExecutionContext childExecutionContext = new ExecutionContext(
           //         childToken);
            //离开节点
            //leave(childExecutionContext, transition);

        }
        Collection tokens = parentToken.getChildren().values();
        for(Iterator iter2 = tokens.iterator();iter2.hasNext();)
        {
            Token k = (Token)iter2.next();
             ExecutionContext childExecutionContext = new ExecutionContext(k);
            //离开节点
            leave(childExecutionContext, getLeavingTransition(k.getName()));
        }

    }

}
